﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ZoeEngine.Framework
{
    public class Entity : ComponentCollection, IEntity
    {
        private string _name;
        private Guid _id;
        private Entity _parent;
        private ComponentManager _manager;

        public Entity(string name = null) : this(name, new EntityComponent[] { }) { }
        public Entity(string name = null, params EntityComponent[] components)
        {
            _name = name;

            if (components.Length > 0)
            {
                for (int i = 0; i < components.Length; i++)
                {
                    this.Add(components[i]);
                }
            }

            _id = Guid.NewGuid();
        }

        public event EventHandler<EntityEventArgs> ParentChanged;
        protected void OnParentChanged(EntityEventArgs e)
        {
            if (ParentChanged != null)
            {
                ParentChanged(this, e);
            }
        }
        protected override void OnComponentAdded(ComponentEventArgs e)
        {
            EntityComponent ec = e.Component;
            ec.Owner = this;
            base.OnComponentAdded(e);
        }

        public string Name
        {
            get
            {
                return _name;
            }
        }
        public Guid ID
        {
            get
            {
                return _id;
            }
        }
        public Entity Parent
        {
            get
            {
                return _parent;
            }
            set
            {
                if (value == this)
                {
                    throw new ArgumentException("An entity cannot be the parent of itself.");
                }

                if (_parent != value)
                {
                    _parent = value;
                    OnParentChanged(new EntityEventArgs(value));
                }
            }
        }
        public ComponentManager Manager
        {
            get
            {
                return _manager;
            }
            set
            {
                _manager = value;
            }
        }
    }
}
